package echo

import (
	"encoding/json"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gorilla/websocket"
	"io"
	"net/http"
	"ws/server/config"
	"ws/server/model"
	"ws/server/websocket/clientManage"
)

func echoReadAll(w http.ResponseWriter, r *http.Request, writeMessage, writePrepared bool) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		g.Log().Error(config.Ctx, "Upgrade:", err)
		return
	}
	defer conn.Close()
	clientManage.AddClient(conn)          // 添加新连接的客户端
	defer clientManage.RemoveClient(conn) // 确保在函数结束时移除客户端
	for {
		mt, b, err := conn.ReadMessage()
		if err != nil {
			if err != io.EOF {
				g.Log().Error(config.Ctx, "client断开连接:", conn.RemoteAddr(), " 错误信息：", err)
			}
			return
		}
		if mt == websocket.TextMessage {
			msg := model.MsgObject{}
			err := json.Unmarshal(b, &msg)
			if err != nil {
				g.Log().Error(config.Ctx, "Error decoding JSON message:", err)
				continue
			}
			// 检查消息类型是否为订阅请求
			switch msg.Type {
			case "sub":
				// 调用Subscribe方法进行订阅
				//log.Println("收到订阅请求:", msg.Topic, msg.TargetCodes)
				clientManage.Subscribe(conn, msg.Topic, msg.TargetCodes)
				// 如果需要响应客户端确认订阅成功，可以在这里添加响应逻辑
			case "unSub":
				clientManage.Unsubscribe(conn, msg.Topic, msg.TargetCodes) // 调用Unsubscribe方法移除订阅
			case "txtMessage":
				err := clientManage.BroadcastToChannel(msg.Topic, websocket.TextMessage, msg, msg.TargetCodes)
				if err != nil {
					g.Log().Error(config.Ctx, "Broadcast error:", err)
				}
			}
		} else if mt == websocket.BinaryMessage {
			// 处理二进制消息的逻辑，这里省略
		}
		//暂时不回写
		//if writeMessage {
		//	if !writePrepared {
		//		err = conn.WriteMessage(mt, b)
		//		if err != nil {
		//			g.Log().Error(config.Ctx, "WriteMessage:", err)
		//		}
		//	} else {
		//		pm, err := websocket.NewPreparedMessage(mt, b)
		//		if err != nil {
		//			g.Log().Error(config.Ctx, "NewPreparedMessage:", err)
		//			return
		//		}
		//		err = conn.WritePreparedMessage(pm)
		//		if err != nil {
		//			g.Log().Error(config.Ctx, "WritePreparedMessage:", err)
		//		}
		//	}
		//} else {
		//	w, err := conn.NextWriter(mt)
		//	if err != nil {
		//		g.Log().Error(config.Ctx, "NextWriter:", err)
		//		return
		//	}
		//	if _, err := w.Write(b); err != nil {
		//		g.Log().Error(config.Ctx, "Writer:", err)
		//		return
		//	}
		//	if err := w.Close(); err != nil {
		//		g.Log().Error(config.Ctx, "Close:", err)
		//		return
		//	}
		//}
	}
}

func EchoReadAllWriter(w http.ResponseWriter, r *http.Request) {
	echoReadAll(w, r, false, false)
}

func EchoReadAllWriteMessage(w http.ResponseWriter, r *http.Request) {
	echoReadAll(w, r, true, false)
}

func EchoReadAllWritePreparedMessage(w http.ResponseWriter, r *http.Request) {
	echoReadAll(w, r, true, true)
}
